// Copyright (c) 2024, yuxinyong and contributors
// For license information, please see license.txt

frappe.ui.form.on('Work Order Scheduling', {

    onload: function(frm) {
        if (frm.is_new()){
            frm.add_child("scheduling_items");
        }
        
		frm.set_query('work_order', "scheduling_items", function(){
			return {
				filters: 
					{
						'status': ["=", "Not Started"],
						'docstatus': ['<', 2],
						'custom_is_repair': frm.doc.purpose === 'Repack'? 1 : 0
					}
			}
		});
	},
	refresh: function(frm) {

	    if (frm.doc.docstatus == 1){
	        frappe.db.get_value('Stock Entry', {'custom_work_order_scheduling': frm.docname}, 'name')
			.then((r) => {
			    if($.isEmptyObject(r.message)) {
	                frm.add_custom_button(__('Create Material Transfer to Work Order'), () => {
			            frappe.call({
				        	method: 'zelin_pp.planning_enhancement.doctype.work_order_scheduling.work_order_scheduling.create_work_order_goods_issue',
					        args: {docname:frm.docname},
					        freeze: true,
			                freeze_message: __("Material Transfer to Work Order..."),
				        })
				        .then( (r) =>{
				            if (r.message){
				                frappe.set_route("List", "Stock Entry", {"name": ["in", r.message]})
				            }
				        })
			        });
			    }
			})
    	}
	}
})
